<template>
  <div class="page">
    <div class="toolbar">
      <h2>交易记录</h2>
      <div class="filters">
        <el-input v-model="filters.search" placeholder="搜索 单号/买家" clearable class="w-240" />
        <el-select v-model="filters.type" placeholder="类型" clearable class="w-140">
          <el-option label="全部" value="" />
          <el-option label="销售" value="sale" />
          <el-option label="退货" value="return" />
        </el-select>
        <el-select v-model="filters.status" placeholder="状态" clearable class="w-160">
          <el-option label="待支付" value="待支付" />
          <el-option label="已支付" value="已支付" />
          <el-option label="待发货" value="待发货" />
          <el-option label="已发货" value="已发货" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已取消" value="已取消" />
          <el-option label="退款中" value="退款中" />
          <el-option label="已退款" value="已退款" />
          <el-option label="已退货" value="已退货" />
        </el-select>
        <el-date-picker v-model="filters.range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        <el-button @click="refresh">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
        <el-button @click="exportCsv">导出</el-button>
      </div>
    </div>

    <el-table :data="pageList" border stripe>
      <el-table-column prop="sn" label="单号" width="180" />
      <el-table-column prop="createdAt" label="日期" width="180" />
      <el-table-column prop="buyer" label="买家" width="140" />
      <el-table-column prop="typeLabel" label="类型" width="100" />
      <el-table-column label="金额" width="120">
        <template #default="{ row }">
          <span :class="{ negative: row.type==='return' }">¥{{ formatMoney(row.displayAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" />
      <el-table-column prop="channel" label="渠道" width="100" />
      <el-table-column prop="operator" label="操作员" width="120" />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="view(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10,20,50]"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="total"
        @size-change="onSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <el-dialog v-model="visible" :title="current?.type==='sale' ? '销售单详情' : '退货单详情'" width="720px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="单号">{{ current?.sn }}</el-descriptions-item>
        <el-descriptions-item label="日期">{{ current?.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="买家">{{ current?.buyer }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ current?.type==='sale' ? '销售' : '退货' }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ formatMoney(current?.displayAmount) }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ current?.status }}</el-descriptions-item>
        <el-descriptions-item label="渠道">{{ current?.channel }}</el-descriptions-item>
        <el-descriptions-item label="操作员">{{ current?.operator }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="current?.items || []" border stripe class="mt-12">
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column prop="qty" label="数量" width="100" />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">¥{{ formatMoney(row.price) }}</template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template #default="{ row }">¥{{ formatMoney(Number(row.qty||0)*Number(row.price||0)) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="visible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
  </template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useOrderStore } from '@/stores/order'
import { useReturnStore } from '@/stores/return'

const orderStore = useOrderStore()
const returnStore = useReturnStore()

const filters = reactive({ search:'', type:'', status:'', range:[] })
const pageSize = ref(10)
const currentPage = ref(1)

const listAll = computed(() => {
  const orders = (orderStore.orders || []).map(o => ({
    id: o.id,
    sn: o.sn,
    createdAt: o.createdAt,
    buyer: o.buyer,
    amount: Number(o.amount || 0),
    displayAmount: Number(o.amount || 0),
    type: 'sale',
    typeLabel: '销售',
    status: o.status,
    channel: o.channel || '',
    operator: o.operator || '系统',
    items: (o.items || []).map(it => ({
      code: it.code,
      name: it.name,
      qty: it.qty,
      price: it.price,
    }))
  }))
  const returns = (returnStore.returns || []).map(r => ({
    id: r.id,
    sn: r.sn,
    createdAt: r.createdAt,
    buyer: r.buyer || '散客',
    amount: Number(r.amount || 0),
    displayAmount: -Number(r.amount || 0),
    type: 'return',
    typeLabel: '退货',
    status: '已退货',
    channel: r.channel || '',
    operator: r.operator || '系统',
    items: (r.items || []).map(it => ({
      code: it.code,
      name: it.name,
      qty: it.qty,
      price: it.price,
    }))
  }))
  return [...orders, ...returns].sort((a,b) => String(b.createdAt).localeCompare(String(a.createdAt)))
})

const filteredList = computed(() => {
  const s = (filters.search || '').toLowerCase()
  const [start, end] = filters.range || []
  return listAll.value.filter(r => {
    if (s && !(r.sn||'').toLowerCase().includes(s) && !(r.buyer||'').toLowerCase().includes(s)) return false
    if (filters.type && r.type !== filters.type) return false
    if (filters.status && r.status !== filters.status) return false
    if (start || end) {
      const d = (r.createdAt || '').slice(0,10)
      if (start && d < start) return false
      if (end && d > end) return false
    }
    return true
  })
})

const total = computed(() => filteredList.value.length)
const pageList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredList.value.slice(start, start + pageSize.value)
})

const visible = ref(false)
const current = ref(null)

onMounted(() => {
  orderStore.initialize()
  returnStore.initialize()
})

function refresh(){ currentPage.value = 1 }
function resetFilters(){ Object.assign(filters, { search:'', type:'', status:'', range:[] }); currentPage.value = 1 }
function exportCsv(){
  const headers = ['单号','日期','买家','类型','金额','状态','渠道','操作员']
  const rows = filteredList.value.map(x => [x.sn, x.createdAt, x.buyer, x.typeLabel, x.displayAmount, x.status, x.channel, x.operator])
  const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '交易记录.csv'
  link.click()
}
function view(row){ current.value = row; visible.value = true }
function onSizeChange(size){ pageSize.value = size; currentPage.value = 1 }
function onPageChange(page){ currentPage.value = page }

function formatMoney(n){ return Number(n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }
</script>

<style scoped>
.page { padding: 16px; }
.toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; gap: 12px; }
.filters { display: flex; gap: 12px; align-items: center; }
.w-240 { width: 240px; }
.w-140 { width: 140px; }
.w-160 { width: 160px; }
.pagination { display:flex; justify-content: flex-end; margin-top: 12px; }
.negative { color: #ff4d4f; }
.mt-12 { margin-top: 12px; }
</style>


